<?php
namespace Addons\WechatOpenPlatform\Controller\Admin;
use Lib\Response;
use Session;
use Models\BaseModel as Model;
use Addons\QyWechat\Helper;

use Addons\WechatOpenPlatform\Services\Wxopenapi;
use Addons\Fission\Helper as FissionHelper;
use Addons\QyWechat\Services\QyWechatApi;
use Addons\QyWechat\Services\ThirdProvider;
require_once(DOXCX_FRAME_PATH . 'fun/library/QyWxCypto/WXBizMsgCrypt.php');

class ActionEvent extends \BaseController
{
	public function index(){
		$timestamp = $_GET['timestamp'];
		$nonce = $_GET['nonce'];
		$msg_signature = $_GET['msg_signature']; 
		$xml = preg_replace("/[\n\s]/", '', file_get_contents('php://input'));
		$appid = substr($_GET["appid"],1);
		$gzh_token = (new Model("qy_gzh_token"))->field("wid")->where(["authorizer_appid"=>$appid])->list_all_array();
		$err_codes["err_code"] = "有错误";
		foreach ($gzh_token as $wid_k => $wid_v) {
			$pubs = (new Model("pubs"))->find($wid_v["wid"]); 
			$user = (new Model("user"))->find($pubs->uid);
			$admin = (new Model('wx_open_confing'))->find(['pid'=>$user->agid]);
			$wx = new \WXBizMsgCrypt($admin->token, $admin->EncodingAESKey, $admin->AppId);
			$msg = ''; 
			$err_code = $wx->DecryptMsg($msg_signature, $timestamp, $nonce, $xml, $msg);
			if($err_code == 0){
				$arr = xml_to_array($msg);
				if($arr["Event"] == "subscribe"){
					$EventKey_id = substr($arr["EventKey"], 8);
				}else if($arr["Event"] == "SCAN"){
					$EventKey_id = $arr["EventKey"];
				}
				//判断如果是群裂变任务的情况下
				if(substr($EventKey_id, 0, 13) == "group_fission"){
					$id = substr($EventKey_id, 13);
    				if(!is_numeric($id)){
    				    $this->help_group_fission($id,$arr);
    				}else{
    				    $this->group_fission($id,$arr);
    				}
					return "success";die;
				}
				if(!is_numeric($EventKey_id)){
					$fission_uses = (new Model("qy_fission_user"))->find(substr($EventKey_id, 5));
					$qyFission = (new Model('qy_fission'))->find($fission_uses->fid);
				}else{
					$qyFission = (new Model("qy_fission"))->find($EventKey_id);
				}
				if($qyFission->status == 2){
					return "success";
				}
				$err_codes["err_code"] = 0;
				$err_codes["wid"] = $qyFission->wid;
				break;
			}
		}
		if($err_code["err_code"] == 0){
			$wid = $err_codes["wid"]; 
			$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		  	$QyWechatApi = QyWechatApi::getInstance();
		 	$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
			$QyWechatApi = Wxopenapi::uniqid($appid,$arr["FromUserName"],$wid);
			$is_status = (new Model("attention"))->find(["ToUserName"=>$arr["ToUserName"],"FromUserName"=>$arr["FromUserName"],"appid"=>$appid,'wid'=>$wid]);
			if(!$attention){
				$is_status = (new Model("attention"))->find(["ToUserName"=>$arr["ToUserName"],"FromUserName"=>$arr["FromUserName"],"appid"=>$appid]);
			}
			if($QyWechatApi["unionid"] || $is_status->UnionID){
				if($arr["Event"] == "subscribe"){
					$EventKey_id = substr($arr["EventKey"], 8);
					if(!is_numeric($EventKey_id)){
						$resArrs = self::unionid($fission_uses->bind_uid);
						$restius = Wxopenapi::send($appid,$arr["FromUserName"],$wid,$qyFission->attention_remind);
						$EventKey_id = $fission_uses->fid;
						$code = $fission_uses->qr_code;
					}else{
						$restius = Wxopenapi::send($appid,$arr["FromUserName"],$wid,$qyFission->attention_remind);
						$code = $qyFission->qr_code;
					} 
					if(!$is_status->id){
						$attention = new Model("attention");
						$attention->wid = $wid;
						$attention->appid = $appid;
						$attention->ToUserName = $arr["ToUserName"];
						$attention->FromUserName = $arr["FromUserName"];
						$attention->CreateTime = $arr["CreateTime"];
						$attention->UnionID = $QyWechatApi["unionid"];
						$attention->EventKey = json_encode(array($EventKey_id),320);
						$attention->Ticket = $arr["Ticket"];
						$attention->status = 1;
						$attention->save();
					}else{
						$EventKey = json_decode($is_status->EventKey,1);
						if(!in_array($EventKey_id,$EventKey)){
							$EventKey[] = $EventKey_id;
							$is_status->EventKey = json_encode($EventKey,320);
						}
						$is_status->status = 1;
						$is_status->save();
					}
			 		$send_code = self::send_code(6,$code,$appid,$arr["FromUserName"],$wid);
				}else if($arr["Event"] == "SCAN"){
					$EventKey_id = $arr["EventKey"];
					if(!is_numeric($EventKey_id)){
						$resArrs = self::unionid($fission_uses->bind_uid);
						if($is_status->UnionID == $resArrs["external_contact"]["unionid"]){
							$restius = Wxopenapi::send($appid,$arr["FromUserName"],$wid,$qyFission->oneself);
							die;
						}
						$EventKey_id = $fission_uses->fid;
						$code = $fission_uses->qr_code;
					}else{
						$code = $qyFission->qr_code;
					}
					$EventKey = json_decode($is_status->EventKey,1);
					if(!in_array($EventKey_id,$EventKey)){
						$EventKey[] = $EventKey_id;
						$is_status->EventKey = json_encode($EventKey,320);
						$send_code = self::send_code(6,$code,$appid,$arr["FromUserName"],$wid);
					}else{
						$restius = Wxopenapi::send($appid,$arr["FromUserName"],$wid,$qyFission->help_repetition);
					}
					$is_status->save();
				}else{
					if($is_status->id){
						$is_status->status = 2;
						$is_status->save();
					}
				}
			}
		}
	  	echo "success";
	} 


	public function send_code($length,$qr_code,$appid,$FromUserName,$wid){
		$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$len = strlen($str)-1;
 		$randstr = '';
 		for ($i=0;$i<$length;$i++) {
	  		$num=mt_rand(0,$len);
	 	 	$randstr .= $str[$num];
 		}
		$save_file = $randstr.".png";
		file_put_contents($save_file, file_get_contents($qr_code));
		$QyWechatApis = Wxopenapi::send_image($appid,$FromUserName,$wid,$save_file);
		if($QyWechatApis["errcode"] == 0){
			unlink($save_file);
 			return true;
		}
 		return false;
	}


	public function unionid($bind_uid){
		$user = (new Model("qy_externalcontact_list"))->find($bind_uid);
		$qyConfigs = (new Model('qy_wechat_config'))->find(['wid'=>$user->wid]);
		// $replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$user->wid]);
		$replyConfig = Helper::getInstance()->get_message_send_config($user->wid);
		$apps = QyWechatApi::getInstance()->get_qy_agent_app($qyConfigs->corp_id,$replyConfig->agent_id,$replyConfig->secret);
		$accessTokens = $apps->access_token;
		$tokens = $accessTokens->getToken()['access_token']; // token 数组  token['access_token'] 字符串
		$urls = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token='.$tokens.'&external_userid='.$user->external_userid;
		$resArrs = json_decode(curlGet($urls),1);
		return $resArrs;
	}


	public function group_fission($id,$data){
		$fission = (new Model("qy_group_fission"))->find($id);
		$wid = $fission->wid;
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
	  	$QyWechatApi = QyWechatApi::getInstance();
	 	$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$QyWechatApi = Wxopenapi::uniqid($fission->authorizer_appid,$data["FromUserName"],$wid);
		if($QyWechatApi["unionid"]){
			$fuser = (new Model("qy_group_fission_user"))->find(["wid"=>$wid,"fid"=>$id,"unionid"=>$QyWechatApi["unionid"]]);
			$fuser->wid = $wid;
			$fuser->fid = $id;
			$fuser->unionid = $QyWechatApi["unionid"];
			$fuser->nickname = $QyWechatApi["nickname"];
			$fuser->avatar = $QyWechatApi["headimgurl"];
			$fuser->ctimes = $QyWechatApi["subscribe_time"];
			$fuser->openid = $QyWechatApi["openid"];
			$fuser->ctime = time(); 
			$fuser->save();
			$content = $fission->welcome_one;
			$content = str_replace('&amp;', "&", $content);
			$content = str_replace('<font style="color: green;">用户昵称&nbsp;</font>', $fuser->nickname, $content);
			$content = str_replace('<font style="color: green;">用户昵称</font>', $fuser->nickname, $content);
			$content = str_replace('&nbsp;', ' ', $content);
			$content = str_replace('<div>', '', $content);
			$content = str_replace('</div>', '', $content);
			$content = str_replace('<br>', '
', $content);
			$restius = Wxopenapi::send($fission->authorizer_appid,$data["FromUserName"],$wid,$content);
			$arr = json_decode($fission->welcome_tow,1);
			$arr["url"] = Helper::getInstance()->get_http_server_name().'/Addons/GroupFission/H5/Fission/index-'.$id.'-'.$fuser->id.'.html';
			if(!$arr["link_pic"]){
				$arr["link_pic"] = "https://assets.weibanzhushou.com/default-cover.png";
			}
			$res = Wxopenapi::send_link($fission->authorizer_appid,$data["FromUserName"],$wid,$arr);
		}		
	}
	
	public function help_group_fission($ids,$data){
	    $id_arr = explode("-",$ids);
	    $id = $id_arr[0];
	    $help_id = $id_arr[1];
		$fission = (new Model("qy_group_fission"))->find($id);
		$help_users = (new Model("qy_group_fission_user"))->find($help_id);
		$wid = $fission->wid;
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
	  	$QyWechatApi = QyWechatApi::getInstance();
	 	$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$QyWechatApi = Wxopenapi::uniqid($fission->authorizer_appid,$data["FromUserName"],$wid);
		if($QyWechatApi["unionid"]){
		    if($QyWechatApi["unionid"] == $help_users->unionid){
			    $restius = Wxopenapi::send($fission->authorizer_appid,$data["FromUserName"],$wid,"扫描自己的二维码无效！");
			    return "success";
		    }
			$status = 4;
			$is_new_friend = 1;
			if($fission->is_new == 1){
				$new = (new Model("qy_externalcontact_list"))->find(["wid"=>$wid,"unionid"=>$QyWechatApi["unionid"]])->field("id")->get_model_array();
				if($new["id"]){
					$status = 2;
					$is_new_friend = 2;
				}
			}
			$fuser = (new Model("qy_group_fission_user"))->find(["wid"=>$wid,"fid"=>$id,"unionid"=>$QyWechatApi["unionid"]]);
			if(!$fuser->id){
				$fuser = new Model("qy_group_fission_user");
				$fuser->wid = $wid;
				$fuser->fid = $id;
				$fuser->is_new_friend = $is_new_friend;
				$fuser->unionid = $QyWechatApi["unionid"];
				$fuser->nickname = $QyWechatApi["nickname"];
				$fuser->avatar = $QyWechatApi["headimgurl"];
				$fuser->ctimes = $QyWechatApi["subscribe_time"];
				$fuser->openid = $QyWechatApi["openid"];
				$fuser->ctime = time(); 
				$fuser->save();
				$help_user = new Model("qy_group_fission_help_user");
				$help_user->wid = $wid;
				$help_user->fid = $id;
				$help_user->pid = $help_id;
				$help_user->help_status = 2;
				$help_user->fail_status = $status;
				$help_user->is_new_friend = $is_new_friend;
				$help_user->help_id = $fuser->id;
				$help_user->help_bind_unionid = $QyWechatApi["unionid"];
				$help_user->ctime = time();
				$help_user->save();
			}
			
			$content = $fission->welcome_one;
			$content = str_replace('&amp;', "&", $content);
			$content = str_replace('<font style="color: green;">用户昵称&nbsp;</font>', $fuser->nickname, $content);
			$content = str_replace('<font style="color: green;">用户昵称</font>', $fuser->nickname, $content);
			$content = str_replace('&nbsp;', ' ', $content);
			$content = str_replace('<div>', '', $content);
			$content = str_replace('</div>', '', $content);
			$content = str_replace('<br>', '
', $content);
			$restius = Wxopenapi::send($fission->authorizer_appid,$data["FromUserName"],$wid,$content);
			$arr = json_decode($fission->welcome_tow,1);
			$arr["url"] = Helper::getInstance()->get_http_server_name().'/Addons/GroupFission/H5/Fission/index-'.$id.'-'.$fuser->id.'.html';
			if(!$arr["link_pic"]){
				$arr["link_pic"] = "https://assets.weibanzhushou.com/default-cover.png";
			}
			$res = Wxopenapi::send_link($fission->authorizer_appid,$data["FromUserName"],$wid,$arr);
		}
	}
}
?> 